package com.fujin.gulimall.ssoserver.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.PostConstruct;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @title: ssoServerController
 * @Author uIn
 * @Date: 2022/3/6 17:49
 * @Version 1.0
 */
@Controller
public class ssoServerController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 跳转登录页面
     * @param url：接收从什么页面跳转到登录页面的url
     * @param model
     * @param redisKey：cookie信息
     * @return
     */
    @GetMapping("/login.html") // 子系统都来这
    public String loginPage(@RequestParam("url") String url,
                            Model model,
                            @CookieValue(value = "redisKey", required = false) String redisKey) {
        // 获取cookie 非空代表就登录过了
        if (!StringUtils.isEmpty(redisKey)) {
            // 告诉子系统他的token，拿着该token就可以查redis了
            return "redirect:" + url + "?token=" + redisKey;
        }
        model.addAttribute("url", url);

        // 子系统都没登录过才去登录页
        return "login";
    }

    /**
     * 登录请求处理
     * @param username
     * @param password
     * @param response
     * @param url：接收登录请求的参数，用于登录成功后返回到之前的页面
     * @return
     */
    @PostMapping("doLogin")
    public String doLogin(String username, String password, HttpServletResponse response,
                          @RequestParam(value="url",required = false) String url){

        if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)){
            //都不为空直接算登录成功
            //登录成功将token信息存入redis
            String uuid = UUID.randomUUID().toString().replace("-", "");
            // 存储cookie， 是在server.com域名下存
            Cookie cookie = new Cookie("redisKey", uuid);
            response.addCookie(cookie);
            redisTemplate.opsForValue().set(uuid,username);

            return "redirect:"+url+"?token="+uuid;
        }
        return "login";
    }
}
